$(function() {

	var winWidth = $(window).width();

	// slide images
	var navs = $('.show-nav li'),
	slide = $('#slide .item-v'),
	slideLen = slide.length,
	pointers = $('#slide .carousel-indicators li');

	// slide scroll
	slide.css('width', winWidth);
	$('#slide .carousel-inner').css('width', 101 * slide.length + '%');

	imgScroll = new IScroll('#wrapper', {
		scrollX: true,
		scrollY: false,
		momentum: false,
		snap: true,
		snapSpeed: 400
	});

	imgScroll.on('scrollStart', function(idx) {
		pointers.eq(idx+1).addClass('active').siblings().removeClass('active');
		navs.eq(idx+1).addClass('active').siblings().removeClass('active');
	})

	var index = 0;

	var changeImg = function(idx) {
		navs.eq(idx).addClass('active').siblings().removeClass('active');
		pointers.eq(idx).addClass('active').siblings().removeClass('active');
		imgScroll.scrollToElement(slide[idx], 500);
	};

	navs.on('click', function() {
		index = $(this).index();
		changeImg(index);
	});
	
	pointers.on('click', function() {
		index = $(this).index();
		changeImg(index);
	});

	setInterval(function() {
		index ++;
		if(index >= slideLen) {
			index = 0;
		}
		changeImg(index);
	}, 5000);

	$(window).on('resize', function() {
		var winWidth = $(window).width();
		slide.css('width', winWidth);
		imgScroll.refresh();
	});

	// click radios
	var radios = $('.search-wrap .radio-inline');
	radios.on('click', function() {
		$(this).find('i').addClass('on');
		$(this).siblings().find('i').removeClass('on');
	});

	// articles pagination
	var articlesWrap = $('.articles-group'),
	morePage = $('.more-page'),
	prev = $('#prev'),
	next = $('#next'),
	page = 2, size = 5, hasNext = true, articles;
	articleTmpl = $('#article-template').html();
		
	morePage.on('click', function() {
		if($(this).is('.loading')) {
			return;
		}
		morePage.addClass('loading');
		$.get('api/article/getlist/?pageindex='+page+'&pagesize='+size, function(data) {
			page ++;
			articles = data.Data.Rows;
			hasNext = data.Data.HasNextPage;
			morePage.removeClass('loading');
			articlesWrap.append(_.template(articleTmpl, {articles: articles}));
			if(!hasNext) {
				morePage.hide();
				return;
			}
		});
	});
	
	$("img.lazy").lazyload();
	$("div.lazy").lazyload({
	    effect: "fadeIn"
	});

});